<template>
  <div class="sci-fi-profile">
    <!-- 背景特效 -->
    <div class="profile-bg-effects">
      <div class="floating-particles">
        <div class="particle" v-for="i in 12" :key="i" :style="getParticleStyle(i)"></div>
      </div>
      <div class="energy-waves">
        <div class="wave"></div>
        <div class="wave"></div>
        <div class="wave"></div>
      </div>
    </div>

    <div class="profile-header">
      <h2 class="profile-title">
        <div class="title-icon">
          <el-icon><UserFilled /></el-icon>
        </div>
        <span>个人中心</span>
        <div class="title-ornament"></div>
      </h2>
      <p class="profile-subtitle">管理您的身份信息</p>
    </div>

    <div class="profile-content">
      <!-- 主信息卡片 -->
      <div class="main-card">
        <div class="card-glow"></div>
        <div class="card-border"></div>

        <div class="user-profile-section">
          <!-- 头像区域 -->
          <div class="avatar-display">
            <div class="avatar-orb-effect"></div>
            <div class="avatar-container">
              <el-upload
                  :action="url"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :on-error="handleUploadError"
                  name="file"
                  accept="image/*"
                  class="avatar-uploader"
              >
                <el-avatar :size="100" :src="userInfo.userAvatar" class="user-avatar">
                  {{ userInfo.username?.charAt(0) || 'U' }}
                </el-avatar>
                <div class="avatar-ring"></div>
                <div class="avatar-pulse"></div>
                <!-- 头像悬停效果 -->
                <div class="avatar-hover">
                  <el-icon><Upload /></el-icon>
                  <span>更换头像</span>
                </div>
              </el-upload>
            </div>
            <div class="user-identity">
              <h3 class="username">{{ userInfo.username || '游客' }}</h3>
              <div class="user-tags">
                <span class="user-id">ID: {{ userInfo.userId || '--' }}</span>
                <div class="status-indicator" :class="userInfo.status === 0 ? 'online' : 'offline'">
                  <div class="status-dot"></div>
                  <span>{{ userInfo.status === 0 ? '在线' : '离线' }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 头像上传提示 -->
          <div class="avatar-upload-section">
            <p class="upload-tip">点击头像上传 • 支持 JPG/PNG 格式 • 最大 2MB</p>
          </div>
        </div>

        <div class="divider-section">
          <div class="divider-line"></div>
          <div class="divider-node">
            <el-icon><Star /></el-icon>
          </div>
          <div class="divider-line"></div>
        </div>

        <!-- 信息编辑表单 -->
        <div class="form-section">
          <div class="section-header">
            <h4 class="section-title">
              <el-icon><Edit /></el-icon>
              身份信息编辑
            </h4>
            <div class="section-actions">
              <el-button class="action-btn" @click="resetForm">
                <el-icon><Refresh /></el-icon>
                重置数据
              </el-button>
            </div>
          </div>

          <el-form
              :model="userInfo"
              :rules="formRules"
              ref="formRef"
              label-width="100px"
              class="sci-fi-form"
          >
            <div class="form-grid">
              <el-form-item label="账号" prop="username" class="form-item">
                <div class="input-container">
                  <div class="input-glow"></div>
                  <el-input
                      v-model="userInfo.username"
                      placeholder="输入您的账号"
                      maxlength="20"
                      show-word-limit
                      class="sci-fi-input"
                      disabled: disabled
                  >
                    <template #prefix>
                      <el-icon><User /></el-icon>
                    </template>
                  </el-input>
                </div>
              </el-form-item>

              <el-form-item label="你的邮箱" prop="email" class="form-item">
                <div class="input-container">
                  <div class="input-glow"></div>
                  <el-input
                      v-model="userInfo.email"
                      placeholder="输入您的联系邮箱"
                      type="email"
                      class="sci-fi-input"
                      disabled :disabled
                  >
                    <template #prefix>
                      <el-icon><Message /></el-icon>
                    </template>
                  </el-input>
                </div>
              </el-form-item>

              <el-form-item label="电话号码" prop="phone" class="form-item">
                <div class="input-container">
                  <div class="input-glow"></div>
                  <el-input
                      v-model="userInfo.phone"
                      placeholder="输入您的电话号码"
                      class="sci-fi-input"
                  >
                    <template #prefix>
                      <el-icon><Phone /></el-icon>
                    </template>
                  </el-input>
                </div>
              </el-form-item>
            </div>

            <el-form-item label="个人介绍" prop="introduction" class="form-item-full">
              <div class="textarea-container">
                <div class="input-glow"></div>
                <el-input
                    type="textarea"
                    v-model="userInfo.introduction"
                    placeholder="写下您的宇宙宣言或个性签名..."
                    :rows="3"
                    maxlength="100"
                    show-word-limit
                    resize="none"
                    class="sci-fi-textarea"
                />
              </div>
            </el-form-item>

            <el-form-item class="form-actions">
              <el-button
                  type="primary"
                  @click="updateInfo"
                  :loading="loading"
                  class="save-btn"
              >
                <div class="btn-glow"></div>
                <el-icon><Check /></el-icon>
                <span>{{ loading ? '更新中...' : '更新' }}</span>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref, reactive, computed} from 'vue'
import { ElMessage } from "element-plus"
import {
  User, Edit, Check, Refresh, Upload,
  Message, Phone, Star, UserFilled
} from "@element-plus/icons-vue"
import http from "@/request/http.js";

const formRef = ref()
const loading = ref(false)
const userInfo = ref({
  userId: '',
  username: '',
  email: '',
  phone: '',
  introduction: '',
  userAvatar: '',
  createTime: '',
  status: 0
})

// 上传配置
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}
const url=computed(() => {
  return http.getUri()+'/user/upload/avatar'
})
// 表单验证规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

// 粒子样式
const getParticleStyle = (index) => {
  const size = Math.random() * 4 + 2
  const duration = Math.random() * 10 + 10
  const delay = Math.random() * 5
  return {
    width: `${size}px`,
    height: `${size}px`,
    left: `${Math.random() * 100}%`,
    animationDelay: `${delay}s`,
    animationDuration: `${duration}s`
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  console.log('开始上传文件:', file.name)
  console.log('文件类型:', file.type)
  console.log('文件大小:', file.size)

  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  loading.value = true
  return true
}

// 头像上传成功处理
const handleAvatarSuccess = (response, file) => {
  loading.value = false
  console.log('上传成功响应:', response)

  if (response.code === 0) {
    let avatarUrl = response.message
    console.log('获取到头像URL:', avatarUrl)

    // 修正URL为MinIO地址
    if (avatarUrl && avatarUrl.includes('192.168.26.179:11003')) {
      const fileName = avatarUrl.split('/').pop()
      avatarUrl = `http://111.119.238.102:9000/vibe-music-data/avatar/2025/10/08/${fileName}`
      console.log('修正为MinIO URL:', avatarUrl)
    }

    userInfo.value.userAvatar = avatarUrl
    ElMessage.success('头像上传成功！')

    // 更新到数据库
    updateUserAvatar(avatarUrl)
  } else {
    ElMessage.error(response.msg || '头像上传失败！')
  }
}

// 错误处理
const handleUploadError = (error) => {
  loading.value = false
  console.error('头像上传失败详情:', error)
  ElMessage.error('上传失败，请稍后重试！')
}

// 更新用户头像到数据库
const updateUserAvatar = async (avatarUrl) => {
  try {
    const updateData = {
      userId: userInfo.value.userId,
      userAvatar: avatarUrl || ''
    }

    const response = await http.put("user/update", updateData)
    if (response.code === 0) {
      console.log('头像信息更新成功')
      await getUserInfo()
    } else {
      console.error('头像信息更新失败:', response.msg)
      ElMessage.error('头像保存失败: ' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('更新头像信息失败:', error)
    ElMessage.error('头像保存失败')
  }
}

// 获取个人信息
const getUserInfo = async () => {
  try {
    const response = await http.get("user/getUserInfo")
    if (response.code === 0) {
      userInfo.value = { ...userInfo.value, ...response.data }
    } else {
      ElMessage.error("获取用户信息失败！")
    }
  } catch (e) {
    console.error("获取用户信息失败！", e)
    ElMessage.error("获取用户信息失败！")
  }
}

// 更新个人信息
const updateInfo = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    if (!userInfo.value.userId) {
      ElMessage.error("用户ID不存在，无法更新！")
      return
    }

    const updateData = {
      userId: userInfo.value.userId,
      username: userInfo.value.username || '',
      phone: userInfo.value.phone || '',
      email: userInfo.value.email || '',
      userAvatar: userInfo.value.userAvatar || '',
      introduction: userInfo.value.introduction || '',
      status: userInfo.value.status || 0
    }

    const hasChanges = updateData.username ||
        updateData.email ||
        updateData.phone ||
        updateData.introduction ||
        updateData.userAvatar

    if (!hasChanges) {
      ElMessage.warning("没有检测到任何修改")
      return
    }

    loading.value = true
    const response = await http.put("user/update", updateData)

    if (response.code === 0) {
      ElMessage.success("个人信息更新成功！")
      await getUserInfo()
    } else {
      ElMessage.error(response.msg || "更新失败！")
    }
  } catch (error) {
    console.error("更新失败:", error)
    ElMessage.error("更新失败，请稍后重试！")
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  getUserInfo()
  ElMessage.info('已重置为原始数据')
}

onMounted(async () => {
  await getUserInfo()
})
</script>

<style scoped>
/* 原有样式保持不变，只添加头像上传器样式 */
.avatar-uploader {
  display: inline-block;
}

.avatar-container {
  position: relative;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-hover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  font-size: 12px;
  border-radius: 50%;
  z-index: 3;
}

.avatar-hover .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.avatar-container:hover .avatar-hover {
  opacity: 1;
}

.upload-tip {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin: 8px 0 0 0;
}
</style>